<script>
import { getDic } from '@/api/dic.api';
export default {
  data() {
    return {
      rules: [],
      fields: [],
    };
  },
  render(h) {
    return (
      <el-form
        ref="mxForm"
        {...{
          props: { ...this.$attrs, model: this.formData, rules: this.rules },
          on: this.$listeners,
        }}
      >
        <el-row>
          {this.fields.map((item) => {
            const subItem = { tag: '', valueLableReverse: true };
            switch (item.tag) {
              case 'el-checkbox-group':
                subItem.tag = 'el-checkbox';
                break;
              case 'el-radio-group':
                subItem.tag = 'el-radio';
                break;
              default:
                subItem.tag = 'el-option';
                subItem.valueLableReverse = false;
                break;
            }
            return (
              <el-col span={item.span || 24}>
                <el-form-item label={item.label} prop={item.prop}>
                  <item.tag
                    vModel={this.formData[item.prop]}
                    {...{ props: item.attrs, on: item.methods }}
                    // value={this.formData[item.prop]}
                    // onInput={(e) => {
                    //   console.log(e);
                    //   this.formData[item.prop] = e;
                    // }}
                  >
                    {item.slots?.map((e) => {
                      return e(h);
                    })}
                    {item.options?.map((e) => {
                      return (
                        <subItem.tag
                          label={subItem.valueLableReverse ? e.value : e.label}
                          value={subItem.valueLableReverse ? e.lable : e.value}
                        >
                          {e.label}
                        </subItem.tag>
                      );
                    })}
                  </item.tag>
                </el-form-item>
              </el-col>
            );
          })}
        </el-row>
      </el-form>
    );
  },
  model: {
    prop: 'formData',
  },
  props: ['formData', 'fieldsConfig'],
  created() {
    this.rules = this.fieldsConfig.reduce((p, c) => {
      return {
        ...p,
        [c.prop]: c.rules,
      };
    }, {});
    Promise.all(
      this.fieldsConfig.map(async (item) => {
        if (item.dicType) {
          return {
            ...item,
            options: await getDic(item.dicType),
          };
        }
        return item;
      })
    ).then((res) => {
      this.fields = res;
    });
  },
};
</script>

